package feces.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.enterprise.inject.New;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.reflect.TypeToken;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import feces.model.Client;
import feces.model.ClientOrder;
import feces.model.ClientOrderList;
import feces.model.Product;
import feces.utility.JSON;
import feces.utility.Utility;
/**
 * 订单的处理文档
 * 
 */
@WebServlet(name="Order", urlPatterns={"/api/order"})
@NoArgsConstructor
public class OrderServlet extends RESTfulServlet{
	/**
	 * 
	 * 字典
	 */
	@NoArgsConstructor(access=AccessLevel.PRIVATE)
	public static final class Directory{
		public static final String ID = "id";
		public static final String ORD_CLI="order_client";
		public static final String GET_CLI="get_client";
		public static final String SEND_INFO="send_info";
		public static final String IS_PAY="is_pay";
		public static final String PRO_ID="pro_id";
		public static final String NUM="num";
		public static final String UNIT="unit";
		public static final String TYPE="type";
		public static final String REQ_INFO="req_info";
		public static final String STATUS="status";
		public static final String CH_INFO="ch_info";
		public static final String REMARK="remark";
		public static final String ORDERDATE="orderdate";
		
	}
	
	static final long serialVersionUID = 7408657878118585468L;



	/**
	 * 响应POST请求
	 * 创建订单
	 * 
	 * @return 订单号
	 */
	@Override
	protected Response<Integer> responseCreate(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		System.out.println("init");
		final List<ClientOrderList> list = JSON.from(
			request.getParameter("pro_list"),
			new TypeToken<List<ClientOrderList>>(){}.getType());
		List<ClientOrderList> li=new ArrayList<ClientOrderList> ();
		System.out.println("insert");
		 Integer ord_cli = Utility.toInteger(request.getParameter(Directory.ORD_CLI));
		if (ord_cli == null) {
			return invalid(null);
		}
		Integer get_cli = Utility.toInteger(request.getParameter(Directory.GET_CLI));
		if (get_cli == null) {
			return invalid(null);
		}
		Integer pro_id = list.get(0).getProduct_id();
		if (pro_id == null) {
			return invalid( null);
		}
		final ClientOrder clo = new ClientOrder();
		clo.setOrder_client(find(Client.class, ord_cli));
		clo.setGet_client( find(Client.class, get_cli));
		clo.setPro_id(pro_id);
		clo.setProducts(list);
		clo.setIs_pay(0);
		clo.setCh_info(request.getParameter(Directory.CH_INFO));
		clo.setRemark(request.getParameter(Directory.REMARK));
		clo.setNum(list.size());
		
		Date date=new Date();
		clo.setOrderdate(new java.sql.Date(date.getTime()));
		
		
		
		clo.setReq_info("快");
		clo.setSend_info(request.getParameter(Directory.SEND_INFO));
		clo.setStatus("已调度");
		clo.setType(request.getParameter(Directory.TYPE));
		clo.setUnit("元");
		if (clo.isValid()) {
			boolean result =  doTransaction(new Runnable() {
					
				@Override
				public void run() {
					System.out.println("run");
					 add(clo);
					 for(ClientOrderList x:list)
					 {
						 
						 x.setOrder_id(clo.getId());
						 
						 add(x);
						 System.out.println("添加订单");
					 }
					 
					 
				}

			});
			if (result) {
				return succeed(clo.getId());
			}
			return exception(null);
		}
		return failed(null);
	}

	/**
	 * 响应DELETE请求
	 * 删除用户信息
	 * 
	 * @return 操作结果
	 */
	@Override
	protected Response<Boolean> responseDelete(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		String parameter = request.getParameter(Directory.ID);
		if (parameter == null) {
			return invalid(false);
		}
		Integer id = Utility.toInteger(parameter);
		if (id == null) {
			return invalid(false);
		}
		final ClientOrder clo =  find(ClientOrder.class, id);
		boolean result =  doTransaction(new Runnable(){

			@Override
			public void run() {
				 remove(clo);
			}
			
		});
		return result ? succeed(true) : exception(false);
	}
	/**
	 * 响应GET请求 获取订单信息信息
	 * 
	 * @return 查询结果，可能为空
	 */
	@Override
	protected Response<List<ClientOrder>> responseRead(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		String na = new String(); 
		na=request.getParameter("name");
		String name=new String(na.getBytes("iso-8859-1"), "utf-8");
		String id = request.getParameter("id");
		String dateStr = request.getParameter(Directory.ORDERDATE);
		String ty=request.getParameter(Directory.TYPE);
		String type=new String(ty.getBytes("iso-8859-1"), "utf-8");
		SimpleDateFormat format=new SimpleDateFormat();
		format.applyPattern("yyyy-MM-dd");
		java.util.Date dt = null;
		if((dateStr!=null)&&(dateStr.isEmpty()==false))
		{
			try {
			  dt = format.parse(dateStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		List<Client> al=null;
		List<ClientOrder> clo=new ArrayList<ClientOrder>();
		if((name!=null)&&(name.isEmpty()==false))
		{
			 al = executeQuery(
				"SELECT DISTINCT e FROM Client e WHERE e.name = ?1", Client.class,name);
			 for(int i=0;i<al.size();i++)
			 {
				 Client cl = al.get(i);
				 clo=executeQuery(
					 "SELECT DISTINCT e FROM ClientOrder e WHERE e.order_client = ?1",
					 ClientOrder.class ,cl);
			 }
		}
		System.out.println("name="+name);
		System.out.println("id="+id);
		if((id!=null)&&(id.isEmpty()==false))
		{
			List<ClientOrder> otemp=new ArrayList<ClientOrder>();
			 otemp = executeQuery(
				"SELECT DISTINCT e FROM ClientOrder e WHERE e.id = ?1", 
				ClientOrder.class,Integer.parseInt(id));
			 if((clo.containsAll(otemp))==false)
			 {
				 clo.addAll(otemp);
			 }
		}
		if(dt!=null)
		{
			List<ClientOrder> otemp=new ArrayList<ClientOrder>();
			 otemp = executeQuery(
				"SELECT DISTINCT e FROM ClientOrder e WHERE e.orderdate = ?1", 
				ClientOrder.class,dt);
			 if((clo.containsAll(otemp))==false)
			 {
				 clo.addAll(otemp);
			 }
		}
		if(type!=null)
		{
			List<ClientOrder> otemp=new ArrayList<ClientOrder>();
			otemp = executeQuery(
				"SELECT DISTINCT e FROM ClientOrder e WHERE e.type = ?1", 
				ClientOrder.class,type);
			if(clo.isEmpty())
			{
				clo.addAll(otemp);
			}
			else if((clo.containsAll(otemp))==false)
			 {
				 clo.addAll(otemp);
			 }
		}
		if (clo != null) {
			return succeed(clo);
		}
		return failed(null);
	}
	/**
	 * 响应PUT请求 修改定单
	 * 
	 * @return 操作结果
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected Response<Boolean> responseUpdate(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		String parameter = request.getParameter(Directory.ID);
		if (parameter == null) {
			return invalid(false);
		}
		Integer id = Utility.toInteger(parameter);
		if (id == null) {
			return invalid(false);
		}
		final ClientOrder type =  find(ClientOrder.class, id);
		parameter = request.getParameter(Directory.ORD_CLI);
		
		if (parameter != null) {
			int idc=Utility.toInteger(parameter);
			type.setOrder_client( find(Client.class, idc));;
		}
		parameter = request.getParameter(Directory.GET_CLI);
		if (parameter != null) {
			id = Integer.valueOf(parameter);
			type.setGet_client( find(Client.class,id));
		}
		parameter = request.getParameter(Directory.PRO_ID);
		if(parameter != null){
			ClientOrderList clol = null;
			id=Utility.toInteger(request.getParameter(Directory.ID));
			clol= find(ClientOrderList.class, id);
			type.setProducts((List<ClientOrderList>) clol);
		}
		if (type.isValid()) {
			boolean result =  doTransaction(new Runnable() {

				@Override
				public void run() {
					update(type);
				}

			});
			return result ? succeed(true) : exception(false);
		}
		return failed(false);
	}
}
